package com.lz.sentinel.project.controller;

import cn.hutool.core.math.MathUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.lz.sentinel.common.entity.RequestVo;
import com.lz.sentinel.common.entity.ResponseVo;
import com.lz.sentinel.common.exception.ServiceException;
import com.lz.sentinel.common.utils.DateUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Random;

/**
 * MQ生产者
 * @author Administrator
 */
@RestController
@RequestMapping(value = "/calc")
public class CalcController {


    // 降级处理方法
    public String handleFallback() {
        return "Degrade response";
    }
    @PostMapping("/send")
    @SentinelResource(value = "/calc/send", blockHandler = "handleBlock", fallback = "handleFallback")
    public ResponseVo send(@RequestBody RequestVo requestVo) {
        System.out.println(DateUtils.getCurr_YYYY_MM_DD_HH_MM_SS_SSS() + "： post发送成功");
        return ResponseVo.success("post发送成功");
    }

    @PostMapping("/send2")
    public ResponseVo send2(@RequestBody RequestVo requestVo) {
        System.out.println(DateUtils.getCurr_YYYY_MM_DD_HH_MM_SS_SSS() + "： post发送成功");
        return ResponseVo.success("post发送成功");
    }


    @GetMapping("/get2")
    @SentinelResource(value = "/calc/get2")
    public ResponseVo get2(@RequestParam(value = "p1", required = false) String p1,
                           @RequestParam(value = "p2", required = false) String p2) {
        System.out.println("p1：" + p1);
        System.out.println("p2: " + p2);
        System.out.println(DateUtils.getCurr_YYYY_MM_DD_HH_MM_SS_SSS() + "： get2发送成功");
        return ResponseVo.success("get2发送成功");
    }

    @PostMapping("/send10")
    @SentinelResource(value = "leakyBucketResource",blockHandler = "handleLeakyBlock")
    public ResponseVo send10(@RequestBody RequestVo requestVo) {
        System.out.println(DateUtils.getCurr_YYYY_MM_DD_HH_MM_SS_SSS() + "：send10 post发送成功");
        return ResponseVo.success("post发送成功");
    }
    public ResponseVo handleLeakyBlock(@RequestBody RequestVo requestVo, BlockException e) {
        ResponseVo result = new ResponseVo();
        result.setErrorCode(-1);
        result.setErrorMsg("Sentinel漏斗算法流量控制了！");
        System.out.println("Sentinel漏斗算法流量请求频繁，控制了！");
        return result;
    }

}